import axios from '../../utils/axios'
const app = getApp()
Page({
	data: {
		officeList: [],
		bindOffice: '',
		isBindBoxShow: false,
		isAuthorize: true,
	},
	onLoad: function (options) {},
	onReady: function () {},
	onShow: function () {
		// 判断登录
		if (app.globalData.userInfo.length === 0) {
			wx.switchTab({
				url: '/pages/user/user',
			})
		}
		// 判断缓存
		else if (!wx.getStorageSync('officeList')) {
			wx.authorize({
				scope: 'scope.userLocation',
				success: () => {
					this.setData({
						isAuthorize: true,
					})
					this.getOffice()
				},
				fail: () => {
					console.log('未授权')
					this.setData({
						isAuthorize: false,
					})
				},
				complete: () => {},
			})
		} else
			this.setData(
				{
					officeList: wx.getStorageSync('officeList'),
				},
				this.initObserver
			)
	},
	onHide: function () {},
	onUnload: function () {
		// 解绑
		if (this._observer) this._observer.disconnect()
	},
	async onPullDownRefresh() {
		wx.showToast({
			title: '加载中...',
			icon: 'loading',
			duration: 3000,
			mask: false,
		})
		await this.getOffice()
		wx.stopPullDownRefresh()
		wx.hideToast()
	},
	onReachBottom: function () {},
	onShareAppMessage: function () {},

	navigationTo(e) {
		wx.navigateTo({
			url: `./detail/courseDetail/courseDetail`,
			success: res => {
				console.log('发送数据')
				res.eventChannel.emit('sendData', {
					data: e.currentTarget.dataset.data,
				})
				console.log('跳转成功', res)
			},
			fail: err => {
				console.log(err, e.currentTarget.dataset.data)
			},
		})
	},
	async getOffice() {
		wx.showLoading({
			title: '基地加载中...',
			duration: 3000,
			mask: true,
		})
		let userInfo = app.globalData.userInfo
		// 获取用户经纬度
		let local = await wx.getLocation({
			type: 'wgs84',
			altitude: false,
			isHighAccuracy: true,
			highAccuracyExpireTime: 5000,
		})
		// 请求附近基地
		let officeListRes = await axios({
			url: '/api/office/radius',
			data: {
				latitude: local.latitude,
				longitude: local.longitude,
				radius: 5000,
			},
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})
		console.log('请求附近基地', officeListRes)
		// 添加用户绑定的基地
		if (userInfo.officeId == null) {
			this.showBindBox()
		} else {
			// 查询自己的基地
			let selfOfficeRes = await axios({
				url: '/api/office/bind',
				data: {
					// officeId: userInfo.officeId,
					openId: userInfo.openId,
				},
				header: {
					Authorization: wx.getStorageSync('token'),
				},
			})
			console.log('selfOfficeRes', selfOfficeRes.data)
			this.setData({
				bindOffice: selfOfficeRes.data,
			})
			officeListRes.data.splice(0, 0, selfOfficeRes.data) // 向基地列表第一个添加绑定基地
		}
		console.log('查询自己的基地', officeListRes.data)
		// 请求基地的课程
		for (let [item, idx] of officeListRes.data.map((item, idx) => [
			item,
			idx,
		])) {
			let courseListRes = await axios({
				url: '/api/course/radius',
				data: {
					officeId: item.id,
					isDel: 0,
				},
				header: {
					Authorization: wx.getStorageSync('token'),
				},
			})
			officeListRes.data[idx].courseList = []
			// push 课程
			courseListRes.data.forEach(item => {
				item.isObServer = false
				officeListRes.data[idx].courseList.push(item)
			})
		}
		// 赋值基地
		this.setData(
			{
				officeList: officeListRes.data,
			},
			this.initObserver
		)
		wx.hideLoading()
		wx.setStorageSync('officeList', officeListRes.data)
	},
	// 绑定基地
	async bindAddress(e) {
		wx.showLoading({
			title: '绑定中...',
			mask: true,
		})
		this.setData({
			isBindBoxShow: false,
		})
		let picker = this.selectComponent('#picker')
		let curAddressId = picker.getValues()[0].id
		let res = await axios({
			url: `/wx/user/{appid}/bind/office?officeId=${curAddressId}`,
			method: 'put',
			header: {
				Authorization: wx.getStorageSync('token'),
			},
		})
		console.log('bindRes', res)
		if (res.statusCode == 200) {
			wx.showToast({
				title: '绑定成功',
				icon: 'success',
				duration: 1500,
			})
			// 交换绑定位置
			this.data.officeList.splice(0, 1, picker.getValues()[0])
			this.setData({
				officeList: this.data.officeList,
			})
			wx.setStorageSync('officeList', this.data.officeList)
		} else {
			wx.showToast({
				title: '绑定失败',
				icon: 'none',
				duration: 1500,
			})
		}
	},
	showBindBox() {
		this.setData({
			isBindBoxShow: !this.data.isBindBoxShow,
		})
	},
	// observer
	// 监听元素进入视窗
	initObserver() {
		console.log('监听元素进入视窗')
		this._observer = wx.createIntersectionObserver(this, {
			// 阈值设置少，避免触发过于频繁导致性能问题
			thresholds: [0.25, 0.75],
			// thresholds: [0, 1],
			// 监听多个对象
			observeAll: true,
		})
		this._observer.relativeTo('.obBlock').observe('.courseItem', res => {
			console.log(res)
			let courseIdx = res.dataset.courseidx
			let officeIdx = res.dataset.officeidx
			let key = `officeList[${officeIdx}].courseList[${courseIdx}].isObServer`
			if (res.intersectionRatio >= 0.8)
				this.setData({
					[key]: true,
				})
			else if (res.intersectionRatio < 0.2)
				this.setData({
					[key]: false,
				})
		})
	},
})
